import paho.mqtt.client as mqtt
import psutil
import time
import json

loopInterval = 3
interface = "enp0s3"
topic = "pc/yourPC/stat"
mqttClientID = "sysstat-yourPC"
serverAddr = "mqtt broker addr"

logiCoreNum = psutil.cpu_count()
phyCoreNum = psutil.cpu_count(logical=False)

client = mqtt.Client()
client._client_id = mqttClientID
client.connect(serverAddr)
client.loop_start()

while True:
    cpuPercent = psutil.cpu_percent(interval=1, percpu=False)
    memPercent = psutil.virtual_memory().percent
    netInterfaces = psutil.net_if_addrs()
    ipStr = str(netInterfaces[interface][0])
    addrIndex = ipStr.find("address='")
    ipAddr = "0"
    if addrIndex != -1:
        ipAddr = ipStr[addrIndex+9:len(ipStr)]
        ipAddr = ipAddr[0:ipAddr.find("'")]
    payload = "{\"cpu\":"+str(cpuPercent)+",\"mem\":"+str(memPercent)

    if ipAddr == "0":
        payload += "}"
    else:
        payload += ",\"ip\":" + "\"" + ipAddr + "\"}"

    client.publish(topic=topic, payload=payload)

    time.sleep(loopInterval)
